<?php
/**
 * Message Class, reflects data retrieved by Message_Model
 * 
 */
class Message extends ArrayObject
{
    function __construct($array)
    {
        parent::__construct($array);
    }

    /**
     * [] (get) of ArrayAccess Interface
     * @param mixed $key
     * @return mixed
     */
    public function offsetGet($key)
    {
        if (preg_match('/^is_/', $key))
        {
            $flag = parent::offsetGet('flag');
        }

        switch($key)
        {
            case 'is_read':
                return ($flag & MASK_READ) ? true : false;
            case 'is_dealt':
                return ($flag & MASK_DEALT) ? true : false;
            case 'is_deleted':
                return ($flag & MASK_DELETED) ? true : false;
            case 'is_cancelled':
            	return ($flag & MASK_CANCELLED) ? true : false;
            default:
                return parent::offsetGet($key);
        }
    }

    /**
     * [] (set) of ArrayAccess Interface
     * @param mixed $key
     * @param mixed $value
     * @return None
     */
    public function offsetSet($key, $value)
    {
        if (preg_match('/^is_/', $key))
        {
            $flag = parent::offsetGet('flag');
        }

        switch($key)
        {
            case 'is_read':
                return parent::offsetSet('flag', self::setBit($flag, $value, 1));
            case 'is_dealt':
                return parent::offsetSet('flag', self::setBit($flag, $value, 2));
            case 'is_deleted':
                return parent::offsetSet('flag', self::setBit($flag, $value, 32));
            case 'is_cancelled':
            	return parent::offsetSet('flag', self::setBit($flag, $value, 3));
            default:
                return parent::offsetSet($key, $value);
        }
    }

    /**
     * Unset a key, of ArrayAccess Interface
     * @param mixed $key
     * @return None
     */
    public function offsetUnset($key)
    {
        if (!preg_match('/^is_/', $key))
        {
           return parent::offsetUnset($key);
        }
    }

    /**
     * Check whether a key exists, of ArrayAccess Interface
     * @param mixed $key
     * @return None
     */
    public function offsetExists($key)
    {
        if (preg_match('/^is_/', $key))
        {
           return parent::offsetExists('flag');
        }
        else
        {
            return parent::offsetExists($key);
        }
    }

    /**
     * set a bit for int $flag, and returns the new flag
     * @param int $flag
     * @param $bitflag
     * @param $position
     * @return int
     */
    private static function setBit($flag, $bitflag, $position)
    {
        if ($bitflag)     // change to 1
        {
            $x       = 1<<($position-1);
            $newflag = $flag|$x;
        }
        else                // change to 0
        {
            $x       = ~(1<<($position-1));
            $newflag = $flag&$x;
        }

        return $newflag;
    }
}
